﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shared.Method
{
    public static class ExtensionMethod
    {
        //public static bool CompareItems(this string first,string second,int offset,int length)
        //{
        //    if (string.IsNullOrEmpty(first) || offset+length>first.Length || offset+length>second.Length) return false;
        //    for(int i = offset; i < offset + length; i++)
        //    {
        //        if (first[i] != second[i]) return false;
        //    }
        //    return true;
        //}

        public static bool CompareItems<TSource>(this TSource[] first, TSource[] second, int offset, int length) where TSource : struct
        {
            if (first == null) return false;
            if (second == null) return false;
            if (offset + length > first.Count()) return false;
            if (offset + length > second.Count()) return false;

            for (int i = offset; i < offset + length; i++)
            {
                if (first[i].Equals(second[i]) == false) return false;
            }

            return true;
        }

        public static decimal ToDecimal(this object obj)
        {
            string str = obj.ToString();
            decimal.TryParse(str, out decimal value);
            return value;
        }

        public static int ToInt32(this object obj)
        {
            string str = obj.ToString();
            int.TryParse(str, out int value);
            return value;
        }

        public static DateTime ToDateTime(this object obj)
        {
            string str = obj.ToString();
            DateTime.TryParse(str, out DateTime value);
            return value;
        }

        public static char ToChar(this object obj)
        {
            string str = obj.ToString();
            return str[0];
        }

        public static bool ToBoolean(this object obj)
        {
            string str = obj.ToString();
            bool.TryParse(str, out bool value);
            return value;
        }

        public static string FormatWith(this string enter, object obj)
        {
            if (string.IsNullOrEmpty(enter)) return string.Empty;

            int indexStart = enter.IndexOf('{');
            int indexEnd = enter.IndexOf('}');

            return enter.Replace(
                enter.Substring(indexStart, indexEnd - indexStart + 1),
                obj.ToString());
        }

        public static string RetainNumber(this string enter)
        {
            if (string.IsNullOrEmpty(enter)) return "-1";

            string retain = string.Empty;
            for (int i = 0; i < enter.Length; i++)
            {
                if (enter[i] >= '0' && enter[i] <= '9')
                {
                    retain += enter[i];
                }
            }
            return retain;
        }
    }
}
